package com.msgserver.mbeans;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import com.msgserver.ejb.services.CompanyServiceLocal;
import com.msgserver.entity.AdminRole;
import com.msgserver.entity.CompanyAdmin;
import com.ocpsoft.pretty.faces.annotation.URLAction;
import com.ocpsoft.pretty.faces.annotation.URLMapping;

@ManagedBean
@ViewScoped
@URLMapping(id = "login", pattern = "/login/", viewId = "/pages/login.jsf")
public class LoginBean {
	
	public LoginBean(){
		System.out.println("init");
	}
	
	private String login;
	private String password;
	
	@EJB(mappedName="MsgServer_EAR/CompanyService/local-com.msgserver.ejb.services.CompanyServiceLocal")
	private CompanyServiceLocal companyService;
	@ManagedProperty(value = "#{globalBean}")
	private GlobalBean gBean;
	
	public String loginAction(){
		CompanyAdmin admin = companyService.getCompanyAdminByLoginAndPassword(getLogin(), getPassword());
		if(admin !=null && admin.getRole()!=null){
			if(admin.getRole().equals(AdminRole.SUPER_ADMIN)){
				gBean.setAdmin(admin);
				return "superadmin?faces-redirect=true";
			}else if(admin.getRole().equals(AdminRole.ADMIN_OF_COMPANY)){
				gBean.setAdmin(admin);
				return "msgAdmin?faces-redirect=true";
			}
		}
		 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"登录失败", "用户名或密码错误!")); 
		 return null;
	}
	public String getLogin() {
		return login;
	}
	public void setLogin(String login) {
		this.login = login;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public GlobalBean getgBean() {
		return gBean;
	}
	public void setgBean(GlobalBean gBean) {
		this.gBean = gBean;
	}
	
	
}
